package com.goa.parse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CheckJson {
    /**
     * 判断16进制是否为合法的JSON串
     * @param hex
     * @return
     */
    public static boolean isJson2Hex(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String str = hex.substring(i, i + 2);
            sb.append((char) Integer.parseInt(str, 16));
        }

        ObjectMapper objectMapper = new ObjectMapper();
        Object json = null;
        try {
            json = objectMapper.readValue(sb.toString(), Object.class);
        } catch (JsonProcessingException e) {
//            e.printStackTrace();
            return false;
        }
        // 打印结果
        try {
            String result = objectMapper.writeValueAsString(json);
            return true;
        } catch (JsonProcessingException e) {
           return false;
        }
    }


    public static String hexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String str = hex.substring(i, i + 2);
            sb.append((char) Integer.parseInt(str, 16));
        }
        return sb.toString();
    }


    public static boolean isJson(String data) {
        System.out.println("isJson========="+data);
        data = data.trim();
        if (data.startsWith("{") || data.startsWith("[")) {
            // 尝试解析 JSON，以确保格式正确
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                objectMapper.readTree(data);
                return true;
            } catch (Exception e) {
                return false; // 解析失败，返回 false
            }
        }
        return false; // 不以 { 或 [ 开头，返回 false
    }
    // 检查字符串是否为十六进制
    public static boolean isHex(String s) {
        return s.matches("^[0-9a-fA-F]+$");
    }



    // 将十六进制字符串转换为字节数组
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    // 将字节数组转换为字符串（仅用于调试输出）
    public static String bytesToString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x ", b));
        }
        return sb.toString().trim();
    }
}
